package com.datapermission.service.impl;

import com.datapermission.annotation.Permission;
import com.datapermission.domain.Product;
import com.datapermission.mapper.ProductMapper;
import com.datapermission.service.ProductService;
import com.datapermission.thread.CustomThreadPoolExecutor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ManualProductServiceImpl implements ProductService {

    private final ProductMapper productMapper;
    private final CustomThreadPoolExecutor customThreadPoolExecutor;

    @Override
    @Permission(tableName = "product")
    public void basicUsageTest() {
        List<Product> products = productMapper.selectProductList();
        log.info("basicUsageTest products: {}", products);
    }

    @Override
    @Permission(tableName = "p")
    public void multipleTableNestingTest() {
        List<Long> orderIdList = Arrays.asList(123L, 456L);
        productMapper.selectProductListByOrderIdList(orderIdList);
    }

    @Override
    @Permission(tableName = "product")
    public void threadTest() {
        // 模拟线程池执行代码
        customThreadPoolExecutor.execute(() -> {
            // 应该获取到的tableName是product
            List<Product> products = productMapper.selectProductList();
            log.info("products: {}", products);
        });
    }

    @Override
    @Permission(tableName = "product")
    public void threadExceptionTest() {
        customThreadPoolExecutor.execute(() -> {
            List<Product> products = productMapper.selectProductList();
            log.info("threadExceptionTest: products: {}", products);
            log.info("即将模拟抛出异常");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            throw new RuntimeException("测试在第二个permission注解抛出异常,测试能否正常把threadLocal清理");
        });
    }


    @Override
    @Permission(tableName = "product")
    public List<Product> selectProductList() {
        return Collections.emptyList();
    }

    @Override
    @Permission(tableName = "p")
    public List<Product> selectProductListByOrderIdList(List<Long> orderIdList) {
        log.info("手动编写的SQL:selectProductListByOrderIdList");
        return productMapper.selectProductListByOrderIdList(orderIdList);
    }


}
